﻿using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
using seejee_Backendium.Core.Interfaces;
using seejee_Backendium.Core.Models;
using seejee_Backendium.Data.Services;

namespace seejee_Backendium.WEB.Controllers
{
    [ApiController]
    [Route("api/[controller]")] // 路由：api/Acc
    public class BILAccListController : ControllerBase
    {
        private readonly IDynamicConnectionService _dynamicConnectionService;
        private readonly ILogger<BILAccListController> _logger;
        private readonly IBILogenAccListService _logenAccListService;
        private readonly IConnectionStringFactory _connectionStringFactory;

        public BILAccListController(IDynamicConnectionService dynamicConnectionService, 
                                    ILogger<BILAccListController> logger, 
                                    IBILogenAccListService logenAccListService,
                                    IConnectionStringFactory connectionStringFactory)
        {
            _dynamicConnectionService = dynamicConnectionService;
            _logenAccListService = logenAccListService;
            _logger = logger;
            _connectionStringFactory = connectionStringFactory; 
        }

        [HttpGet("{cOperatorName}")] // 修改路由模板，使用路径参数
        public async Task<ActionResult<IEnumerable<DataSourcesDto>>> GetAccList([FromRoute] string cOperatorName)
        {
            try
            {
                var result = await _logenAccListService.GetAllAccListAsync(cOperatorName);

                if (result == null || !result.Any())
                {
                    _logger.LogWarning("未找到cOperatorName为[{cOperatorName}]的数据源记录", cOperatorName);
                    return NotFound($"未找到cOperatorName={cOperatorName}的记录");
                }

                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取cOperatorName[{cOperatorName}]的数据源记录失败", cOperatorName);
                return StatusCode(500, "服务器内部错误：获取数据失败");
            }
        }
        [HttpGet("DB/{DBContent}")]
        public async Task<IActionResult> DBContent([FromRoute] int DBContent)
        {
            try
            {
                // 获取数据库连接信息
                BIDBContentDto dbInfo = await _logenAccListService.GetDBContentAsync(DBContent);
                if (dbInfo == null)
                {
                    _logger.LogWarning("DBContent[{DBContent}]的数据源记录不存在", DBContent);
                    return NotFound($"DBContent {DBContent} 的数据源记录不存在");
                }

                // 先构建连接字符串
                string connectionString = _dynamicConnectionService.BuildConnectionString(dbInfo);

                // 然后测试构建好的连接字符串是否能连接
                bool isConnected = await _dynamicConnectionService.TestConnectionAsync(connectionString);
                if (!isConnected)
                {
                    return BadRequest("数据库连接测试失败");
                }

                // 将连接字符串存储到工厂中（这里需要注入IConnectionStringFactory）
                 _connectionStringFactory.SetDataSourcesConnectionString(connectionString);

                return Ok(new
                {
                    Success = true,
                    ConnectionString = connectionString,
                    Message = "数据库连接测试成功"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取DBContent[{DBContent}]时发生错误", DBContent);
                return StatusCode(500, "服务器内部错误");
            }
        }
    }
}